package com.laikan.reader.core.service;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.v4.app.NotificationCompat;
import android.widget.RemoteViews;
import com.laikan.reader.R;
import com.laikan.reader.core.utils.FileUtil;
import com.laikan.reader.core.utils.UrlManagerUtil;
import com.socks.library.KLog;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/***
 * 更新版本
 *
 * @author wangchunguang
 */
public class UpdateService extends Service {

    private static final String UPDATE_TAG = "UpdateService";

    private static final int DOWNLOAD_FAIL = 0;
    private static final int DOWNLOAD_SUCCESS = 1;
    private static final int TIMEOUT = 10 * 1000;// 超时时间
    private static final String down_url = UrlManagerUtil.getString("update.mHtmlUrl", "");
    /***
     * 创建通知栏
     */
    RemoteViews contentView;
    private String app_name;
    private NotificationManager notificationManager;
    private Notification notification;
    private Intent updateIntent;
    private PendingIntent pendingIntent;
    private int notification_id = 0;
    private int totalSize;// 文件总大小
    private Handler mHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {

            super.handleMessage(msg);
            switch (msg.what) {
                case DOWNLOAD_SUCCESS:
                    // 下载完成，点击安装
                    Intent intent = new Intent(Intent.ACTION_VIEW);
                    String type = getMIMEType(FileUtil.updateFile);
                    intent.setDataAndType(Uri.fromFile(FileUtil.updateFile), type);
                    pendingIntent = PendingIntent.getActivity(UpdateService.this, 0, intent, 0);
                    NotificationCompat.Builder builder = new NotificationCompat.Builder(UpdateService.this);
                    builder.setContentTitle(app_name);
                    builder.setContentText("下载成功，点击安装");
                    builder.setContentIntent(pendingIntent);

                    notificationManager.notify(notification_id, builder.build());

                    stopService(updateIntent);
                    break;
                case DOWNLOAD_FAIL:
                    NotificationCompat.Builder builder_fail = new NotificationCompat.Builder(UpdateService.this);
                    builder_fail.setContentTitle(app_name);
                    builder_fail.setContentText("下载失败");
                    builder_fail.setContentIntent(pendingIntent);
                    //                    notification.setLatestEventInfo(UpdateService.this, app_name, "下载失败", pendingIntent);
                    break;
                default:
                    stopService(updateIntent);
                    break;
            }
        }
    };

    @Override
    public IBinder onBind(Intent arg0) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        app_name = intent.getStringExtra("app_name");
        // 创建文件
        FileUtil.createApkFile(app_name);

        createNotification();
        createThread();
        return super.onStartCommand(intent, flags, startId);
    }

    /***
     * 开线程下载
     */
    public void createThread() {

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    long downloadSize = downloadUpdateFile(down_url, FileUtil.updateFile.toString());
                    if (downloadSize == totalSize) {
                        // 下载成功
                        mHandler.sendEmptyMessage(DOWNLOAD_SUCCESS);
                    }
                }catch (Exception e) {
                    e.printStackTrace();
                    mHandler.sendEmptyMessage(DOWNLOAD_FAIL);
                }
            }
        }).start();
    }

    public void createNotification() {
        notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
        notification = new Notification();
        notification.icon = R.mipmap.ic_launcher;
        // 这个参数是通知提示闪出来的值.
        notification.tickerText = "开始下载";

        notification.contentView = contentView;

//        updateIntent = new Intent(this, MainActivityFW.class);// 这个activity需要传启动这个service的那个activity
        updateIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        pendingIntent = PendingIntent.getActivity(this, 0, updateIntent, 0);

        notification.contentIntent = pendingIntent;

        notificationManager.notify(notification_id, notification);

    }

    /***
     * 下载文件
     *
     * @return
     *
     * @throws MalformedURLException
     */
    public long downloadUpdateFile(String down_url, String file) throws Exception {
        int down_step = 5;// 提示step
        int downloadCount = 0;// 已经下载好的大小
        int updateCount = 0;// 已经上传的文件大小

        InputStream inputStream = null;
        OutputStream outputStream = null;
        HttpURLConnection httpURLConnection = null;
        URL url = new URL(down_url);

        try {
            httpURLConnection = (HttpURLConnection)url.openConnection();
            if (httpURLConnection != null) {
                httpURLConnection.setConnectTimeout(TIMEOUT);
                httpURLConnection.setReadTimeout(TIMEOUT);
                // 获取下载文件的size
                totalSize = httpURLConnection.getContentLength();
                if (httpURLConnection.getResponseCode() == 404) {
                    throw new Exception("fail!");
                }
                inputStream = httpURLConnection.getInputStream();
                outputStream = new FileOutputStream(file, false);// 文件存在则覆盖掉
                byte buffer[] = new byte[1024];
                int readsize = 0;
                while ((readsize = inputStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, readsize);
                    downloadCount += readsize;// 时时获取下载到的大小

                    /**
                     * 每次增张5%
                     */
                    if (updateCount == 0 || (downloadCount * 100 / totalSize - down_step) >= updateCount) {
                        updateCount += down_step;
                        notificationManager.notify(notification_id, notification);
                    }
                }
            }
        }catch (Exception e) {
            // TODO Auto-generated catch block
            KLog.e(UPDATE_TAG, "下载失败：" + e);
        }finally {
            if (null != httpURLConnection) {
                httpURLConnection.disconnect();
                httpURLConnection = null;
            }
            if (null != inputStream) {
                inputStream.close();
                inputStream = null;
            }
            if (null != outputStream) {
                outputStream.close();
                outputStream = null;
            }
        }

        return downloadCount;
    }

    /**
     * 获取类型
     *
     * @param f
     *
     * @return
     */
    private String getMIMEType(File f) {
        String type = "";
        String fName = f.getName();
        String end = fName.substring(fName.lastIndexOf(".") + 1, fName.length()).toLowerCase();
        if (end.equals("m4a") || end.equals("mp3") || end.equals("mid") || end.equals("xmf") || end.equals("ogg") || end.equals("wav")) {
            type = "audio";
        }else if (end.equals("3gp") || end.equals("mp4")) {
            type = "video";
        }else if (end.equals("jpg") || end.equals("gif") || end.equals("png") || end.equals("jpeg") || end.equals("bmp")) {
            type = "image";
        }else if (end.equals("apk")) {
            type = "application/vnd.android.package-archive";
        }else {
            type = "*";
        }
        if (end.equals("apk")) {
        }else {
            type += "/*";
        }
        return type;
    }

}
